package com.enation.app.shop.front.policyInsurance.appController;


import com.enation.app.shop.front.api.utils.IdCardUtil;
import com.enation.app.shop.front.api.inpolicy.entity.InPolicy;
import com.enation.app.shop.front.policyInsurance.appController.InPolicyUtils.InsPolicyUtils;
import com.enation.app.shop.front.policyInsurance.service.InpolicyFrameManageMapper;
import com.enation.framework.action.JsonResult;
import com.enation.framework.database.IDaoSupport;
import com.enation.framework.util.DateUtil;
import com.enation.framework.util.JsonResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

/**
 * 养殖端保险订单管理
 */
@Scope("prototype")
@Controller
@RequestMapping("/app/farmerInsurancManage")
public class InsurancFrameController {
    Logger logger = LoggerFactory.getLogger(InsurancFrameController.class);
    @Autowired
    private IDaoSupport iDaoSupport;

    @Autowired
    private InpolicyFrameManageMapper inpolicyFrameManageMapper;

    /**
     * 查看当前会员全部保险订单 养殖端
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("/getAllInpolicy")
    public JsonResult getAllInpolicyInfo(Integer userid,String str) {
        List list;
        if(str!=null){
            //全部保单
            if (str.equals("ALL")) {
                try {
                    List<InPolicy> inPolicyList = inpolicyFrameManageMapper.getAllInPolicyInfo(userid);
                    list = InsPolicyUtils.chageInPolicyStatus(inPolicyList);
                    if (list.size() >= 0) {
                        return JsonResultUtil.getObjectMessageJson(list,"首页得到保险订单列表!");
                    }
                }catch (Exception e){
                    return JsonResultUtil.getErrorJson("获取保单失败!!");
                }
            }
            //核保中
            if (str.equals("HBZ")) {
                try {
                    List<InPolicy> checkInpolicyInfoList = inpolicyFrameManageMapper.getCheckInpolicyInfo(userid);
                    list = InsPolicyUtils.chageInPolicyStatus(checkInpolicyInfoList);
                    if (list.size() >= 0) {
                        return JsonResultUtil.getObjectMessageJson(list, "获取数据成功!");
                    }
                }catch (Exception e){
                    return JsonResultUtil.getErrorJson("没有保单数据!!");
                }
            }

            //待支付
            if (str.equals("DZF")) {
                try{
                    List<InPolicy> bearInpolicyInfoList = inpolicyFrameManageMapper.getUnpaidInpolicyInfo(userid);
                    list = InsPolicyUtils.chageInPolicyStatus(bearInpolicyInfoList);
                    if (list.size() >= 0) {
                        return JsonResultUtil.getObjectMessageJson(list, "获取数据成功!");
                    }
                }catch (Exception e){
                    return JsonResultUtil.getErrorJson("获取保单失败!");
                }
            }
            //已承保
            if (str.equals("YCB")) {
                try{
                    List<InPolicy> bearInpolicyInfoList = inpolicyFrameManageMapper.getBearInpolicyInfo(userid);
                    list = InsPolicyUtils.chageInPolicyStatus(bearInpolicyInfoList);
                    if (list.size() >= 0) {
                        return JsonResultUtil.getObjectMessageJson(list, "获取数据成功!");
                    }
                    return JsonResultUtil.getErrorJson("没有已承保的保单数据!");
                }catch (Exception e){
                    return JsonResultUtil.getErrorJson("获取保单失败!");
                }
            }
            //历史保单
            if(str.equals("LSBD")){
                try {
                    List<InPolicy> historyInpolicyInfoList = inpolicyFrameManageMapper.getHistoryInpolicyInfo(userid);
                    list=InsPolicyUtils.chageInPolicyStatus(historyInpolicyInfoList);
                    if(list.size() >= 0){
                        return JsonResultUtil.getObjectMessageJson(list,"获取数据成功!");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    return JsonResultUtil.getErrorJson("获取失败!");
                }
            }
        }
        return JsonResultUtil.getErrorJson("获取信息失败,str不能为空!");
    }

    /**
     * 获取保单详情
     * @param inPolicy_id
     * @return
     */
    @ResponseBody
    @RequestMapping("/getInPolicyDetail")
    public JsonResult getInPolicyDetail(Integer inPolicy_id){
        InPolicy inPolicy = inpolicyFrameManageMapper.getBytinPolicy_id(inPolicy_id);
        if(inPolicy.getCase_date()==null){
            inPolicy.setCase_date(new Timestamp(System.currentTimeMillis()));
        }
        if(inPolicy!=null){
            return JsonResultUtil.getObjectMessageJson(inPolicy,"获取数据成功!");
        }
        return JsonResultUtil.getErrorJson("获取数据失败!");
    }
    /**
     * 投保
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("/addInPolicy")
    public JsonResult addInPolicy(@RequestBody InPolicy inPolicy){
        try {
            //验证身份证号
            inPolicy.setWarranty_number(createSn());
            if (!IdCardUtil.validate(inPolicy.getPolicy_idcard().trim())) {
                return JsonResultUtil.getErrorJson("请输入正确的身份证号码！");
            }else{
                inPolicy.setPolicy_idcard(inPolicy.getPolicy_idcard());
            }
            //验证手机号
            if (inPolicy.getPolicy_mobile().length() != 11) {
                return JsonResultUtil.getErrorJson("请输入正确的手机号！");
            }else{
                inPolicy.setPolicy_mobile(inPolicy.getPolicy_mobile());
            }
            inPolicy.setStatus(0);
//            inPolicy.setIs_payment(0);
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            inPolicy.setCreated_at(timestamp);
            inPolicy.setUpdate_time(timestamp);
            inPolicy.setBegin_time(timestamp);
            Calendar cal = Calendar.getInstance();
            cal.setTime(inPolicy.getBegin_time());
            cal.add(Calendar.MONTH, 12);
            inPolicy.setEnd_time(new Timestamp(cal.getTime().getTime()-1000*60*60*24));
            inPolicy.setReceiver_id(1004);
            inPolicy.setReceiver_name("测试人员");
        }catch (Exception e){
            e.printStackTrace();
            this.logger.error("创建保单异常!");
        }
        int a = inpolicyFrameManageMapper.addInPolicy(inPolicy);
        if (a != 1) {
            return JsonResultUtil.getErrorJson("创建保单失败!");
        } else {
            return JsonResultUtil.getSuccessJson("创建保单成功!");
        }
    }

    /**
     * 创建保单号（日期+两位随机数）
     */
    private String createSn(){
        boolean isHave = true;  //数据库中是否存在该保单
        String sn = "";			//保单号
        //如果存在当前保单
        while(isHave) {
            StringBuffer  snSb = new StringBuffer("ZPlay2018") ;
            snSb.append(DateUtil.getDateline()+"");
            snSb.append(new Random().nextInt(100-10)+10);
            String sql = "SELECT count(*) FROM rbt_inpolicy WHERE warranty_number = '" + snSb.toString() + "'";
            int count = this.iDaoSupport.queryForInt(sql);
            if(count == 0) {
                sn = snSb.toString();
                isHave = false;
            }
        }
        return sn;
    }

}